﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using UDS.Components;
using UDS.Entity;

namespace UDS.SubModule.UnitiveDocument.DocumentFlowPages
{
    /// <summary>
    /// SignDocument 的摘要说明。
    /// </summary>
    public partial class DisplayDocumentPage : Page
    {
        private DocumentAction _action;
        private int _docID;
        private bool _flowState;
        private string _userName;
        private DocumentInfo _doc;

        protected int ReturnPage
        {
            get;
            private set;
        }

        protected DocumentInfo CurrentDoc
        {
            get { return _doc; }
        }

        protected FlowStyle CurrentFlowStyle
        {
            get;
            private set;
        }

        protected override void OnInit(EventArgs e)
        {
            _docID = Int32.Parse(Request.QueryString["DocID"]);
            _userName = SiteContext.Current.UserName;
            ReturnPage = QSUtil.GetPositiveInt32("ReturnPage", 1);
            _doc = DocumentInfo.GetDocumentInfo(_docID);

            #region event handlers
            cmdSignIn.Click += cmdSignIn_Click;
            cmdBack.Click += cmdBack_Click;
            cmdPostilNext.Click += cmdPostilNext_Click;
            cmdPostilFaile.Click += cmdPostilFaile_Click;
            cmdPostilFinish.Click += cmdPostilFinish_Click;
            cmdCancelSignIn.Click += cmdCancelSignIn_Click;
            cmdReturn.RedirectUrl = "ListDocument.aspx?DisplayType=" + ReturnPage;
            #endregion event handlers

            if (_doc == null)
            {
                // The document does not exist.
                SiteContext.Current.Alert("指定的文档不存在。", true);
            }
            else
            {
                InitControl();
                Bind();
            }

            base.OnInit(e);
        }

        protected string FormatPostilAttachmentLink(DocumentPostil p)
        {
            if (p != null && p.File != null)
            {
                string path = p.File.FullVirtualPath;
                if (!string.IsNullOrEmpty(path))
                {
                    return "<a href='" + HttpUtility.HtmlAttributeEncode(ResolveUrl(path)) + "' target='_blank'>" + HttpUtility.HtmlEncode(p.File.FileName) + "</a>";
                }
            }
            return "&nbsp;";
        }

        private void InitControl()
        {
            _action = DocumentInfo.GetDocumentStatus(_docID, _userName);

            if (_action == DocumentAction.Receive) //签收状态
            {
                cmdSignIn.Visible = true;
                cmdCancelSignIn.Visible = false;
                cmdPostilNext.Visible = false;
                cmdPostilFaile.Visible = false;
                cmdPostilFinish.Visible = false;
                cmdBack_selector.Visible = false;

                _flowState = false;
            }
            else if (_action == DocumentAction.Pending) //一般批阅状态
            {
                cmdSignIn.Visible = false;
                cmdCancelSignIn.Visible = true;
                cmdPostilNext.Visible = true;
                cmdPostilFaile.Visible = true;
                cmdPostilFinish.Visible = true;
                cmdBack_selector.Visible = true;

                _flowState = true;
            }
            else if (_action == DocumentAction.Reject) //撤消状态，现在已经没有撤消状态了，只有文档是草稿才能删除
            {
                cmdSignIn.Visible = true;
                cmdCancelSignIn.Visible = false;
                cmdPostilNext.Visible = false;
                cmdPostilFaile.Visible = false;
                cmdPostilFinish.Visible = false;
                cmdBack_selector.Visible = false;

                _flowState = false;
            }
            else if (_action == DocumentAction.CounterSignPending) //会签状态批阅
            {
                cmdSignIn.Visible = false;
                cmdCancelSignIn.Visible = true;
                cmdPostilNext.Visible = true;
                cmdPostilFaile.Visible = true;
                cmdPostilFinish.Visible = false;
                cmdBack_selector.Visible = true;

                _flowState = true;
            }
            else //查看状态
            {
                cmdSignIn.Visible = false;
                cmdCancelSignIn.Visible = false;
                cmdPostilNext.Visible = false;
                cmdPostilFaile.Visible = false;
                cmdPostilFinish.Visible = false;
                cmdBack_selector.Visible = false;

                _flowState = false;
            }
        }


        private void Bind()
        {
            Debug.Assert(_doc != null);
            int FlowID = _doc.FlowID;
            int StepID = _doc.StepID;

            // 确定当前步骤是否有结束流程的权利
            bool rightToFinish = false;
            FlowStep step = FlowStep.GetStep(_doc.FlowID, _doc.StepID);
            if (step != null)
            {
                rightToFinish = step.RightToFinish;
            }
            cmdPostilFinish.Visible = cmdPostilFinish.Visible && rightToFinish;

            //流程批阅状态并且按照项目流转
            projectRow.Visible = false;
            if (_flowState && DocumentInfo.IsFlowByProject(_userName, _docID))
            {
                projectRow.Visible = true;
                ddlProject.Items.Clear();

                var projects = Project.GetProjects(_userName);
                foreach (var p in projects)
                {
                    ddlProject.Items.Add(new ListItem(p.Name, p.ID.ToString()));
                }
            }

            fieldRepeater.DataSource = FlowStyleDescription.GetStyleDescriptionByFlow(_doc.FlowID);
            fieldRepeater.DataBind();
            attachmentRepeater.DataSource = DocumentFile.GetAttachments(_doc.DocID);
            attachmentRepeater.DataBind();

            var postils = DocumentPostil.GetDocumentPostils(_doc.DocID);
            postilRepeater.Visible = (postils.Count > 0);
            if (postilRepeater.Visible)
            {
                postilRepeater.DataSource = postils;
                postilRepeater.DataBind();
            }
            placeHolderPostil.Visible = (cmdPostilNext.Visible || cmdPostilFaile.Visible || cmdPostilFinish.Visible);

            if (cmdBack_selector.Visible)
            {
                var steps = DocumentInfo.GetDocumentPath(_doc.DocID);
                if (steps.Length > 2)
                {
                    for (int i = 0; i < steps.Length - 1; i++) // ignoe the last step (the current one)
                    {
                        var s = steps[i];
                        ListItem listItem = new ListItem();
                        listItem.Text = s.Name;
                        listItem.Value = s.ID.ToString();
                        docPathList.Items.Add(listItem);
                    }

                    // select the last step
                    docPathList.Items[docPathList.Items.Count - 1].Selected = true;
                }
            }
        }

        private int GetSelectedProjectID()
        {
            if (projectRow.Visible)
            {
                if (ddlProject.Items.Count == 0)
                {
                    return -1; // No project
                }
                return int.Parse(ddlProject.SelectedValue);
            }

            return 0;
        }

        private void cmdSignIn_Click(object sender, EventArgs e)
        {
            DocumentInfo.SignInDocument(SiteContext.Current.UserName, _docID);
            cmdSignIn.Visible = false;

            SiteContext.Current.ClientRefresh(true);
        }

        private void cmdCancelSignIn_Click(object sender, EventArgs e)
        {
            DocumentInfo.CancelSignInDocument(SiteContext.Current.UserName, _docID);
            SiteContext.Current.ClientRefresh(true);
        }

        private void cmdPostilNext_Click(object sender, EventArgs e)
        {
            int projectId = GetSelectedProjectID();
            if (projectId < 0)
            {
                SiteContext.Current.Alert("没有上级项目！");
                return;
            }

            int r = DocumentInfo.PostDocument(SiteContext.Current.UserName, _doc.DocID, projectId, txtPostil.Text, 2, fileUpload.PostedFile);
            if (r != 0)
            {
                SiteContext.Current.Alert(DocumentInfo.GetErrorMessage(r, _docID, false));
            }
            SiteContext.Current.ClientRefresh(true);
        }

        private void cmdPostilFaile_Click(object sender, EventArgs e)
        {
            int projectId = GetSelectedProjectID();

            DocumentInfo.RejectDocument(
                SiteContext.Current.UserName,
                _doc.DocID,
                txtPostil.Text,
                projectId,
                2,
                fileUpload.PostedFile);
            SiteContext.Current.ClientRefresh(true);
        }

        private void cmdPostilFinish_Click(object sender, EventArgs e)
        {
            int projectId = GetSelectedProjectID();
            DocumentInfo.FinishDocument(
                SiteContext.Current.UserName,
                _doc.DocID,
                txtPostil.Text,
                projectId,
                0,
                fileUpload.PostedFile);
            SiteContext.Current.ClientRefresh(true);
        }

        private void cmdBack_Click(object sender, EventArgs e)
        {
            int orderId = -1;
            if (docPathList.Items.Count > 1)
            {
                orderId = int.Parse(docPathList.SelectedValue);
            }
            int projectId = GetSelectedProjectID();
            DocumentInfo.BackDocument(
                SiteContext.Current.UserName,
                _doc.DocID,
                txtPostil.Text,
                projectId,
                2,
                fileUpload.PostedFile,
                orderId);

            SiteContext.Current.ClientRefresh(true);
        }
    }
}